import React, { useState, useEffect, useMemo } from "react";
import {
  initialSchema,
  formatForArrayTable,
  formatArrayCollap,
} from "@/components/schema-form-render/utils";
import { TableOperate } from "@/components/SelfIcon";
import { getButtons } from "@/utils/with-btns";
import { Popconfirm } from "antd";
import {
  registerListTableEvent,
  registerListButtonEvent,
  getExportParams,
} from "../utils";
import _ from "lodash";
import { FormattedMessage } from "umi";
import { storage } from "@ey-utils/utils";
import OpContent from "@/biz-components/table-render/components/operation-content";
/**
 * 所有按钮初始化
 * @param hooks context
 * @param events  注册事件
 * @param params 执行事件参数
 * @returns  void
 */
export function useEventsRegister(hooks: any, events: any, params: any) {
  const { loading, searchButtons, buttons, tableButtons, validator } = params;
  useEffect(() => {
    if (!events) return;
    if (events?.tableButtonsEvents) {
      registerListTableEvent(
        hooks?.current?.tableButtonsEvents,
        events?.tableButtonsEvents,
        params
      );
    }
    if (events?.buttonsEvents) {
      registerListButtonEvent(
        hooks?.current?.buttonsEvents,
        events?.buttonsEvents,
        params
      );
    }
  }, []);

  // 生成搜索按钮
  const getSearchButtons = () =>
    getButtons(
      { loading, buttons: searchButtons },
      hooks.current.buttonsEvents
    );

  // 生成新增按钮
  const getTableTopButton = () =>
    getButtons(
      { loading, buttons: buttons },
      hooks.current.buttonsEvents,
      validator
    );

  // 列表行项目操作按钮
  // @ts-ignore
  const operations = (
    id: string,
    row: any,
    extraPropsForOp: any,
    idx: number
  ) => {
    const res: any = [];
    tableButtons?.map((o: any, index: any) => {
      if (validator?.checkColBtns && !validator.checkColBtns(o.key, row)) {
      } else {
        if (
          ["shanchu", "qiyong", "jinyong", "chongzhi", "chehui"].includes(o.key)
        ) {
          res.push(
            <Popconfirm
              title={<FormattedMessage id="buttons.yesOrNo" />}
              onConfirm={() => {
                hooks.current.tableButtonsEvents[o?.props?.hook](id, row, idx);
              }}
            >
              <TableOperate type={o.key} text={o.label} key={index} />
            </Popconfirm>
          );
        } else {
          res.push(
            <TableOperate
              key={o.key}
              type={`icon-${o.key}`}
              text={o.label}
              onClick={() => {
                hooks.current.tableButtonsEvents[o?.props?.hook](id, row, idx);
              }}
            />
          );
        }
      }
    });
    if (res.length > 3) {
      const head = res.slice(0, 2);
      const rest = res.slice(2);
      return [<OpContent left={head} hide={rest} />];
    } else {
      return res;
    }
  };

  return {
    getSearchButtons,
    getTableTopButton,
    operations,
  };
}

/**
 * 数据初始化
 * @param metasConfig 传入自己构建配置信息
 * @param remoteMetasConfig 通过 pageCode 拿
 * @param type 单据类型
 * @param needGroup 是否需要分组
 * @returns 初始化后 的配置信息
 */
export function useInitData(
  metasConfig: any,
  remoteMetasConfig: any,
  type: "NORMAL" | "SEARCH" | "DETAIL" = "SEARCH",
  needGroup: boolean = false,
  eventMap?: any
) {
  const [smConfigs, setConfigs] = useState<any>({});
  useEffect(async () => {
    if (metasConfig?.code || remoteMetasConfig?.code) {
      const sss: any = initialSchema(
        metasConfig?.code ? metasConfig : remoteMetasConfig,
        type,
        needGroup,
        "",
        false,
        eventMap
      );

      await formatForArrayTable(sss.ArrayTableList, sss.schema, "NORMAL");
      await formatArrayCollap(sss.ArrayColList, sss.schema, "NORMAL");
      setConfigs(sss);
    }
  }, [metasConfig?.code, remoteMetasConfig?.code]);
  return smConfigs;
}

export function useCacheData(match: any) {
  const data = storage.getItem(match?.path);
  let searchParams = {};
  if (data?.queryKeys) {
    searchParams = getExportParams(data.queryKeys);
  }
  return [searchParams];
}
